<?php
/**
 * 前台用户管理
 */
namespace backend\modules\admin\controllers;

use Yii;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;

use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\User;
use common\models\Branch;
use common\models\Logtransfer;

use yii\web\Response;
use common\models\Tree;

class UserController extends Controller
{

    public function init()
    {
        parent::init();
    }
    /**
     * role列表
     * 使用dateprovider自动分页
     */
    public function actionIndex($realname='',$tel='')
    {

        $where = ['status'=>0];
        if($realname) $where['realname'] = $realname;
        if($tel) $where['tel'] = $tel;

        $dataProvider = new ActiveDataProvider([
            'query' => User::find()->where($where)->orderBy('id ASC'),
            'pagination' => [
                'pageSize' => ADMINPAGENUM,
            ],
        ]);

//        $branch = Branch::findOne(['id' => $branch_id]);
//        $title =  $branch->name;

//        $branchMenu =  Branch::getMenu($branch_id);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'realname'=>$realname,
            'tel'=>$tel,
//            'branchMenu' => $branchMenu,
//            'title'=>$title,
        ]);

    }

    /**
     * 添加用户
     * 使用了AR类
     * 并添加了验证，如所需项为空，则添加失败
     */
    public function actionCreate()
    {
        $model = new User(); 
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'添加失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];

        if($model->load(Yii::$app->request->post()))
            {
                // echo $model->join_time;exit;
                if($model->validate())
                {
 
                    $model->save(); 
                    return $this->render('//msg',[
                        'url'=>'index',//跳转页面，若为goback,则返回上一页
                        'msg'=>'添加成功',//跳转自定义信息
                        'ms'=>5000,//延迟时间
                        'msg_type'=>'success'//消息类型，success,error,close
                    ]);
                }
                else
                {
                    return $this->render('//msg',$rs);
                }
        }
        else{
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }


     /**
     * 修改用户
     */
    public function actionUpdate($id)
    {
        $user = User::findOne(['id' => $id]);
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'修改失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];

        if($user->load(Yii::$app->request->post()))
        {
            if($user->validate())
            {
                $user->save(); 
                return $this->render('//msg',
                [
                    'url'=>'index',//跳转页面，若为goback,则返回上一页
                    'msg'=>'修改成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
            }
            else
            {
                return $this->render('//msg',$rs);
            }
        }
        else
        {
            return $this->render('update', [
                'model' => $user,
            ]);
        }
    }

    /**
     * 删除用户
     */
    public function actionDelete($id)
    {
        Yii::$app->response->format=Response::FORMAT_JSON;

        $user = User::findOne(['id' => $id]);

        $user->status = -1;
        $res = $user->save();
        if($res){
            return ['msg'=>'删除成功','status'=>-1];
        }else{
            return ['msg'=>'删除失败','status'=>0];
        }

    }


    public function actionView($id)
    {

        $user = User::findOne(['id' => $id]);
        $transfer = Logtransfer::find()->where(['uid'=>$id])->select('branch_from,branch_to,ttime')->all();
         return $this->render('view', [
            'user' => $user,
             'log_transfer'=>$transfer
        ]);
    }

    /**
     * 党员更改支部功能
     */
    public function actionTransfer(){
        $request = Yii::$app->request;
        $uid = $request->get('uid');
        if(!$uid){
            return $this->render('//msg',
                [
                    'url'=>'',//跳转页面，若为goback,则返回上一页
                    'msg'=>'不存在党员编号，请确认用户id',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'error'//消息类型，success,error,close
                ]);
        }

        $branches = Branch::find()->where(['status'=>0])->orderBy('listorder DESC,id DESC')->all();
        $model = User::findOne($uid);

        //修改字段
        if($request->post()){
            //更改user表中支部记录
            $now_branch = Branch::find()->where(['id'=>$model->branch_id])->select('name')->scalar();//记录原始的党支部信息

            $data = $request->post('User');//获取前台传递数据;
            $data_user['User']['branch_id'] = $data['branch_id'];
            $model->load($data_user);
            $st = $model->save();

            //添加更改记录日志
            $model_log = new Logtransfer();

            $new_branch = Branch::find()->where(['id'=>$data['branch_id']])->select('name')->scalar();
            if($now_branch == $new_branch){
                return $this->render('//msg',
                    [
                        'url'=>'',//跳转页面，若为goback,则返回上一页
                        'msg'=>'支部没有变化,请选择其他支部',//跳转自定义信息
                        'ms'=>1000,//延迟时间
                        'msg_type'=>'error'//消息类型，success,error,close]
                    ]);
            }

            $data_log['Logtransfer'] = [
                'uid'=>$uid,//迁移的党员
                'op_id'=>$_SESSION['adminuser']['id'], //操作者
                'branch_from'=> $now_branch, //当前党支部
                'branch_to'=> $new_branch, //新党支部
                'ttime'=>strtotime($data['certify_time']), //迁移时间
                'op_time'=>time(), //操作时间
                'note'=>$data['note'] //备注信息
            ];

            $model_log->load($data_log);

            $model_log->insert();
            return $this->render('//msg',
                [   'url'=>'index',//跳转页面，若为goback,则返回上一页
                    'msg'=>'迁移成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close]
                ]
            );
        }

        //当前党员基本信息
        return $this->render('transfer',['model'=>$model,'branches'=>$branches]);
    }



    public function treeMenu(){
 
            $branches =Branch::find('')->asArray()->where(['status'=>'0'])->all();//查询所有分类 

            /** 实现党支部的层级下拉框  **/
            $tree= new Tree();//实例化tree
            $tree->icon = array('│ ','├─ ','└─ ');//设置一个树形数组
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';//设置空格占位符
            $str="<li value='\$id'   \$selected >\$spacer \$name</li>";//生成树形结构基本代码
            
            $Tbranches=[];
            foreach($branches as $key=>$branch)//遍历循环 对单个分类数据进行处理 并获取层级
            {
                $Tbranches[$branch['id']]['parentid']=$branch['parentid'];
                $Tbranches[$branch['id']]['name']=$branch['name'];
                $Tbranches[$branch['id']]['parentid_node']=$branch['parentid']?' class="child-of-node-'.$branch['parentid'].'"':'';//如果 $cat['parentid']不为空就赋值如果为空就赋值空
                $Tbranches[$branch['id']]['level']=Branch::get_level($branch['id'],$branches);//传递调用get_level方法
                $Tbranches[$branch['id']]['id']=$branch['id'];
                //$branches[$key]['selected']=in_array($branch['id'],$selectids)?'selected':'';
            }
           
            $tree->init($branches);//初始化$cate
            $branchstr = $tree->get_tree(0, $str,0);//生成选择框字符串

    }

}